import 'package:chewie/chewie.dart';
import 'package:flutter/material.dart';
import 'package:video_player/video_player.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
      ),

      home: VideoPlayerChewiePage(),
    );
  }
}

class VideoPlayerChewiePage extends StatefulWidget {
  const VideoPlayerChewiePage({super.key});

  @override
  State<VideoPlayerChewiePage> createState() => _VideoPlayerChewiePageState();
}

class _VideoPlayerChewiePageState extends State<VideoPlayerChewiePage> {
  late final VideoPlayerController _videoPlayerController;
  late final ChewieController _chewieController;
  @override
  void initState() {
    super.initState();

    initVideo();
  }

  void initVideo() async {
    _videoPlayerController = VideoPlayerController.asset(
      'asset/videos/test.mp4',
    );
    await _videoPlayerController.initialize();
    _chewieController = ChewieController(
      videoPlayerController: _videoPlayerController,

      autoPlay: true, // 是否自动播放
      looping: false, // 是否循环播放
      showControls: true, // 是否显示控制条
      showControlsOnInitialize: true, // 是否在初始化时显示控制条
      aspectRatio: 16 / 9, // 视频比例
      fullScreenByDefault: false, // 是否默认全屏
      allowFullScreen: true, // 是否允许全屏

      draggableProgressBar: true, // 是否允许拖动进度条
      materialProgressColors: ChewieProgressColors(
        playedColor: Colors.red,
        bufferedColor: Colors.blueGrey,
        backgroundColor: Colors.grey,
      ),
      showOptions: false, // 是否显示选项按钮
      zoomAndPan: true, // 是否允许缩放和拖动
      maxScale: 2.5,
      allowMuting: true, // 是否允许静音
      hideControlsTimer: Duration(seconds: 3), // 控制条隐藏时间
      errorBuilder: (BuildContext context, String errorMessage) {
        return Text('加载错误');
      },
      allowedScreenSleep: false, // 是否允许屏幕休眠
      useRootNavigator: false, // 是否使用根导航器
    );

    setState(() {});
  }

  @override
  void dispose() {
    super.dispose();
    _videoPlayerController.dispose();
    _chewieController.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('视频播放')),
      body: SizedBox.expand(
        child: Column(
          children: [
            _videoPlayerController.value.isInitialized
                ? AspectRatio(
                    aspectRatio: 16 / 9,
                    child: Chewie(controller: _chewieController),
                  )
                : CircularProgressIndicator(),
          ],
        ),
      ),
    );
  }
}
